import random

from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView

from . import serializers, constants
from .libs.captcha.captcha import captcha
from django import http
# Create your views here.
from .libs.yuntongxun.sms import CCP
import logging
logger = logging.getLogger("django")

class ImageCodeView(View):
    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        # 获取到验证码的文字和图片
        text, img = captcha.generate_captcha()
        # 与ｒｅｄｉｓ数据库交互
        redis_conn = get_redis_connection('verify_codes')
        # 设置过期时间３００秒
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        return http.HttpResponse(img, content_type='image/jpg')

class CheckImageCodeView(View):
    def get(self,request):
        uuid = request.GET.get('uuid')
        image_code = request.GET.get('image_code')
        redis_conn = get_redis_connection('verify_codes')
        image_code_server = redis_conn.get('img_%s' % uuid)
        print(image_code_server)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            print('图片过期')
            return http.JsonResponse({'code': '1', 'errmsg': '图形验证码失效'})
        # 比较验证码
        image_code_server = image_code_server.decode()  # bytes转字符串
        if image_code.lower() != image_code_server.lower():  # 转小写后比较
            print('图片错误')
            return http.JsonResponse({'code': '1', 'errmsg': '输入图形验证码有误'})
        else:
            return http.JsonResponse({'code': '0', 'errmsg': '输入图形验证码正确'})



class SMSCodeView(GenericAPIView):
    """
    短信验证码
    """
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self, request, mobile):
        """
        创建短信验证码
        """
        # 判断图片验证码, 判断是否在60s内
        # print(1)
        serializer = self.get_serializer(data=request.query_params)
        # print(2)
        serializer.is_valid(raise_exception=True)
        # print(3)
        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)

        # 保存短信验证码与发送记录
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        print(4)
        # 发送短信验证码
        try:
            sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
            ccp = CCP()
            ruresult=ccp.send_template_sms(mobile, [sms_code, sms_code_expires], 1)
        except Exception as e:
            logger.error("发送短信失败--->[%s]" % mobile)
            return http.JsonResponse({"message": "发送失败"},status=500)
        return http.JsonResponse({"message": "OK","code":"0"})